import React, { useState } from 'react';
import { Tree, Button, Input, Space, Modal, Select, Card, Typography, message } from 'antd';
import { EditOutlined, DeleteOutlined, PlusOutlined } from '@ant-design/icons';

const { Option } = Select;
const { Title, Text } = Typography;

const mockTrees = [
    {
        id: 1,
        name: '产品目录',
        data: [
            {
                key: 1,
                value: 1,
                title: '电子产品',
                children: [
                    {
                        key: 2,
                        value: 2,
                        title: '手机',
                        children: [
                            { key: 4, value: 4, title: '智能手机' },
                            { key: 5, value: 5, title: '功能手机' },
                        ],
                    },
                    {
                        key: 3,
                        value: 3,
                        title: '电脑',
                        children: [
                            { key: 6, value: 6, title: '笔记本电脑' },
                            { key: 7, value: 7, title: '台式机' },
                        ],
                    },
                ],
            },
            {
                key: 8,
                value: 8,
                title: '家居用品',
                children: [
                    { key: 9, value: 9, title: '家具' },
                    { key: 10, value: 10, title: '厨具' },
                ],
            },
        ],
    },
    {
        id: 2,
        name: '公司组织架构',
        data: [
            {
                key: 11,
                value: 11,
                title: '总部',
                children: [
                    {
                        key: 12,
                        value: 12,
                        title: '技术部',
                        children: [
                            { key: 13, value: 13, title: '前端开发' },
                            { key: 14, value: 14, title: '后端开发' },
                        ],
                    },
                ],
            },
        ],
    },
];

const EditableTree = () => {
    const [selectedTreeId, setSelectedTreeId] = useState(mockTrees[0].id);
    const [trees, setTrees] = useState(mockTrees);
    const [editingKey, setEditingKey] = useState(null);
    const [newTitle, setNewTitle] = useState('');
    const [isModalVisible, setIsModalVisible] = useState(false);
    const [newNodeTitle, setNewNodeTitle] = useState('');
    const [selectedParentKey, setSelectedParentKey] = useState(null);

    const currentTree = trees.find((t) => t.id === selectedTreeId);

    // 递归查找并更新节点
    const updateTreeData = (nodes, key, callback) =>
        nodes.map((node) => {
            if (node.key === key) {
                return callback(node);
            }
            if (node.children) {
                return { ...node, children: updateTreeData(node.children, key, callback) };
            }
            return node;
        });

    // 编辑
    const handleEdit = (key, title) => {
        setEditingKey(key);
        setNewTitle(title);
    };

    const handleSave = (key) => {
        const newTrees = trees.map((tree) =>
            tree.id === selectedTreeId
                ? {
                    ...tree,
                    data: updateTreeData(tree.data, key, (node) => ({
                        ...node,
                        title: newTitle,
                    })),
                }
                : tree
        );
        setTrees(newTrees);
        setEditingKey(null);
        setNewTitle('');
    };

    // 删除
    const handleDelete = (key) => {
        const deleteNode = (nodes, key) =>
            nodes
                .map((node) => {
                    if (node.key === key) return null;
                    if (node.children) {
                        return { ...node, children: deleteNode(node.children, key) };
                    }
                    return node;
                })
                .filter(Boolean);

        const newTrees = trees.map((tree) =>
            tree.id === selectedTreeId ? { ...tree, data: deleteNode(tree.data, key) } : tree
        );
        setTrees(newTrees);
    };

    // 添加节点
    const handleAddNode = () => {
        if (!newNodeTitle) {
            message.warning("请输入节点标题");
            return;
        }

        const newKey = Date.now();
        const newNode = { key: newKey, value: newKey, title: newNodeTitle, children: [] };

        const addNode = (nodes, parentKey) =>
            nodes.map((node) => {
                if (node.key === parentKey) {
                    return { ...node, children: [...(node.children || []), newNode] };
                }
                if (node.children) {
                    return { ...node, children: addNode(node.children, parentKey) };
                }
                return node;
            });

        const newTrees = trees.map((tree) =>
            tree.id === selectedTreeId
                ? {
                    ...tree,
                    data: selectedParentKey
                        ? addNode(tree.data, selectedParentKey)
                        : [...(tree.data || []), newNode], // 根节点下添加
                }
                : tree
        );

        setTrees(newTrees);
        setIsModalVisible(false);
        setNewNodeTitle('');
        setSelectedParentKey(null);
    };

    // 渲染节点
    const formatTreeNode = (node) => {
        const isEditing = editingKey === node.key;
        return {
            key: node.key,
            value: node.value,
            title: isEditing ? (
                <Space style={{ display: 'flex', alignItems: 'center' }}>
                    <Input
                        size="small"
                        value={newTitle}
                        onChange={(e) => setNewTitle(e.target.value)}
                        onPressEnter={() => handleSave(node.key)}
                        style={{ width: 160 }}
                    />
                    <Button type="primary" size="small" onClick={() => handleSave(node.key)}>
                        保存
                    </Button>
                </Space>
            ) : (
                <Space style={{ display: 'flex', alignItems: 'center' }}>
                    <Text>{node.title}</Text>
                    <EditOutlined
                        style={{ color: '#1890ff', cursor: 'pointer' }}
                        onClick={() => handleEdit(node.key, node.title)}
                    />
                    {/* 新增子节点按钮 */}
                    <PlusOutlined
                        style={{ color: '#52c41a', cursor: 'pointer' }}
                        onClick={() => {
                            setSelectedParentKey(node.key);
                            setIsModalVisible(true);
                        }}
                    />
                    <DeleteOutlined
                        style={{ color: '#ff4d4f', cursor: 'pointer' }}
                        onClick={() => handleDelete(node.key)}
                    />
                </Space>
            ),
            children: node.children ? node.children.map((child) => formatTreeNode(child)) : undefined,
        };
    };

    return (
        <div style={{ display: 'flex', padding: 24, gap: 24, background: '#f5f5f5', height: 'calc(100vh - 64px - 10px)', }}>
            {/* 左侧树选择 */}
            <Card
                title={<Title level={5} style={{ margin: 0 }}>树选择</Title>}
                style={{ width: 260, borderRadius: 8, boxShadow: '0 2px 8px rgba(0,0,0,0.1)', height: 'calc(100vh - 24px - 24px - 70px)'}}
            >
                <Select
                    value={selectedTreeId}
                    onChange={(value) => setSelectedTreeId(value)}
                    style={{ width: '100%', marginBottom: 12 }}
                >
                    {trees.map((tree) => (
                        <Option key={tree.id} value={tree.id}>
                            {tree.name}
                        </Option>
                    ))}
                </Select>
                <Button
                    type="primary"
                    icon={<PlusOutlined />}
                    block
                    onClick={() => {
                        setSelectedParentKey(null); // 强制根节点
                        setIsModalVisible(true);
                    }}
                >
                    添加根节点
                </Button>
            </Card>

            {/* 右侧树展示 */}
            <Card
                title={<Title level={5} style={{ margin: 0 }}>{currentTree?.name || '请选择树'}</Title>}
                style={{ flex: 1, borderRadius: 8, boxShadow: '0 2px 8px rgba(0,0,0,0.1)',height: 'calc(100vh - 24px - 70px - 24px)' }}
            >
                {currentTree ? (
                    <Tree
                        treeData={currentTree?.data.map((node) => formatTreeNode(node))}
                        defaultExpandAll
                        style={{ background: '#fff', padding: 12, borderRadius: 6 }}
                    />
                ) : (
                    <Text type="secondary">请先选择一棵树</Text>
                )}
            </Card>

            {/* 添加节点弹窗 */}
            <Modal
                title="添加新节点"
                open={isModalVisible}
                onOk={handleAddNode}
                onCancel={() => setIsModalVisible(false)}
                okText="确认"
                cancelText="取消"
            >
                <div style={{ marginBottom: 16 }}>
                    <Text>节点标题：</Text>
                    <Input
                        placeholder="请输入节点标题"
                        value={newNodeTitle}
                        onChange={(e) => setNewNodeTitle(e.target.value)}
                        style={{ marginTop: 6 }}
                    />
                </div>
            </Modal>
        </div>
    );
};

export default EditableTree;
